<?php
#input
$raw = file_get_contents("php://input");
$input = json_decode($raw, true);
$action = $input['action'];
$payload = $input['payload'];

#entrances
if ($action == 'add') {
    insertData($payload);
} else if ($action == 'load') {
    $res = json_encode(loadData(), JSON_UNESCAPED_UNICODE);
    log_file($res);
    echo $res;
}

function loadData()
{
    $sql = "SELECT * FROM retraining_records";
    $res = db_exec($sql);
    $out = array();
    while ($row = mysqli_fetch_assoc($res)) {
        array_push($out, $row);
    }
    return $out;
}

function insertData($payload)
{
    #(id, name, date, type, title, duration, examiner, timestamp)
    $name = $payload['name'];
    $date = $payload['date'];
    $type = $payload['type'];
    $title = $payload['title'];
    $duration = $payload['duration'];
    $examiner = $payload['examiner'];
    $time = date('Y-m-d H:i:s');
    $sql = "INSERT INTO retraining_records VALUES (null , '{$name}' , '{$date}' , '{$type}' , '{$title}' , {$duration} , '{$examiner}' , '{$time}')";
    log_file($sql);
    db_exec($sql);
}

function log_file($text)
{
    $content = '[' . date("Y-m-d H:i:s") . '] ' . $text;
    $file_path = './logfile.txt';
    $file = fopen($file_path, 'a');
    fwrite($file, "{$content}\r\n");
    fclose($file);
}

function db_exec($sql)
{
    $dbhost = 'localhost';
    $dbusr = 'cdapp';
    $dbpwd = 'gzzxjjwt1';
    $bdname = 'cdapp';
    $link = mysqli_connect($dbhost, $dbusr, $dbpwd, $bdname);
    if (!$link) {
        #log_file(mysqli_connect_errno() . ': ' . mysqli_connect_error());
        return null;
    }
    mysqli_query($link, "set character set 'utf8'");
    mysqli_query($link, "set names 'utf8'");
    if ($result = mysqli_query($link, $sql)) {
        mysqli_close($link);
        return $result;
    }
    #log_file(mysqli_error($link));
    mysqli_close($link);
    return null;
}
